package com.elong.common.http;

import org.apache.http.Consts;
import org.apache.http.client.HttpClient;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

/**
 * HttpClientUtil
  * @Title: HttpClientUtil
  * @Desription 工具类
  * @author Guanguo.Gao
  * @date 2015年2月2日 下午8:24:36
 */
public class HttpClientUtil {
    
    private HttpClientUtil(){
	
    }
    
    private HttpClient client;
    
    //连接管理器
    private static PoolingHttpClientConnectionManager manager = null;
    
    //默认buff size
    private static int maxBuffSize = 8192;
    
    //socket超时
    private static int socketTimeOut = 25000;
    
    //每个host最多的连接数
    private static int maxConnectionPerHost = 20;
    
    //最多的连接数
    private static int maxTotalConnections = 100;
    
    /**
     * 保存client示例的本地变量
     */
    private static ThreadLocal<HttpClientUtil> threadSession = new ThreadLocal<>();

    /**
     * getter method for client
     * @return the client
     */
    public HttpClient getClient() {
        return client;
    }

    /**
     * setter method for client
     * @Description the client to set
     * @param client 
     */
    public void setClient(HttpClient client) {
        this.client = client;
    }
    
    public static HttpClient getInstance(){
        manager = new PoolingHttpClientConnectionManager();
        manager.setDefaultMaxPerRoute(maxConnectionPerHost);
        manager.setMaxTotal(maxTotalConnections);
        //set socket option
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeOut)
                .build();
        manager.setDefaultSocketConfig(socketConfig);
        //set connection config
        ConnectionConfig connConfig = ConnectionConfig.custom()
                        .setCharset(Consts.UTF_8)
                        .setBufferSize(maxBuffSize)
                        .build();
        manager.setDefaultConnectionConfig(connConfig);
	return getInstance(new PoolingHttpClientConnectionManager());
    }
    
    public static HttpClient getInstance(HttpClientConnectionManager connManager){
	HttpClientUtil util = threadSession.get();
	if(util == null){
	    util = new HttpClientUtil();
	    HttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
	    util.setClient(client);
	    threadSession.set(util);
	}
	return util.getClient();
    }
    
}
